#encoding=utf-8
'''
Created on 2014-12-9

@author: cooler
'''
import sys, logging, os, os.path
sys.path.append(os.getcwd()+"/utils" )

from Config import initConfig
config = initConfig()
from Database import ArtMysql as db_session

# from artmdb import ArtMysql
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy import create_engine, MetaData
from sqlalchemy import Column, String,Integer
from sqlalchemy.orm import sessionmaker
from utils import Redisfactory
from suface_sqlalchemy import SQLAlchemySuface
from CreateRSTR import createRSTR,getMd5Value,checkSign,getYSTKKM
import json

from datetime import datetime 

#----  全局变量，过期时间
EXPIRE_TIME = 60*60
EXPIRE_TIME_ENROLL_FLAG = 60*2
EXPIRE_TIME_USERINFO = 60*60*24*15
EXPIRE_TIME_MAJOR_INFO = 60*60*24


logger = logging.getLogger('database')
logger.setLevel(logging.DEBUG)


mdb_read = SQLAlchemy()
mdb_write = SQLAlchemySuface()



def getOne(sql):
    try:
        logger.info(sql)
        engine = mdb_read.get_engine()
        # logger.info(str(engine))
        con = engine.connect()
        DB_Session = sessionmaker(bind=engine)
        session = DB_Session()
        cur = session.execute(sql)
        result = cur.fetchone()
    except Exception as e:
        logger.exception(str(e))
        results=False
    return result


def getMany(sql):
    try:    
        logger.info(sql)
        engine = mdb_read.get_engine()
        # logger.info(str(engine))
        DB_Session = sessionmaker(bind=engine)
        session = DB_Session()
        cur = session.execute(sql)
        results = cur.fetchall()
    except Exception as e:
        logger.exception(str(e))
        results=False
    return results

def executeSQL(sql):
    try:
        logger.info(sql)
        engine = mdb_write.get_engine()
        DB_Session = sessionmaker(bind=engine)
        session = DB_Session()
        session.execute(sql)
        session.commit()
        session.close() 
        res = True   
    except Exception as e:
        logger.exception(str(e))
        res = False
    return res


def convertDataDict(keystr,data):
    if data==None:
        return data
    keys = keystr.split(",")
    data_dict,i = {},0
    for key in keys:
        data_dict[str(key)]=data[i]
        i=i+1
    return data_dict

def convertDatasDict(keys,datas):
    if datas==None:
        return datas
    datas_list,i = [],0
    for data in datas:
        datas_list.append(convertDataDict(keys,data))
    return datas_list









